import Taro, { Component } from '@tarojs/taro'
import { View, Text, Button, Icon } from '@tarojs/components'
import Lyclistitem from '../components/movie-showing-item'
import LycCollectlistitem from '../components/collect-showing-item'
import { AtModal, AtModalHeader, AtModalContent, AtModalAction,AtFloatLayout} from 'taro-ui'
import './index.scss'
import banner from '../../assets/images/banner@2x.png'

export default class Index extends Component {
  config = {
      navigationBarTitleText: '首页',
      backgroundColor: '#F2F2F2',
      window: {
        backgroundColor: "#F2F2F2"
      }
  }
  
  constructor(props) {
    super(props);
    this.state = {
      search:'',
      clist: [],
      vlist: [],
      clist_content:[],
      clist_title:[],
      pageNum: 1,
      contentid:1,
      isOpened: false,
      collectOneIsOpened:false,
      collectOneSelected:0,
      selectedContent:[],
      collectList:[],
      collectList_content:[],
      collectList_title:[],
      clearSearch:false
    }; 
  }
  //回到顶部
  goTop = e => { 
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  }
  handleClose = e =>{
    // 关闭收藏的歌词
    this.setState({isOpened:false}) 
  }
  handelChange (e) {
    this.setState({search:e.target.value})
  }
  
  onAddone(e){
    // console.log(e)
    let arr = wx.getStorageSync("geci") || [];
    let temp = []
    temp.push(this.state.clist_content[e])
    temp.push(this.state.clist_title[e])
    arr.unshift(temp);
    console.log(arr)
    // console.log(wx.getStorageSync("geci"))
    wx.setStorageSync("geci", arr)
    wx.showToast({
      title: '添加到收藏',
      icon: 'none',
      duration: 1000
    })
  }
  collectClick = type => {
    // this.addOneCollect('很好');
    let arr = wx.getStorageSync("geci") || [];
    let content = []
    let title = []
    
    for(let i in arr){
      
      content.push(arr[i][0])
      title.push(arr[i][1])
    }
    this.setState({
      [`isOpened`]: true,
      collectList_content:content,
      collectList_title:title
    })
  }
  closeModal = (type, msg) => {
    console.log(type)
    this.setState({
      [`isOpened`]: false
    })

    // Taro.showToast({
    //   icon: 'none',
    //   title: msg
    // })
  }

  showOneSelected = e => {
    // 打开单个收藏的词条，设置当前选中的一条收藏的编号 0 1 2 ...
    console.log(e)
    let temp = []
    temp.push(this.state.collectList_content[e])
    temp.push(this.state.collectList_title[e])

    this.setState({
      collectOneSelected: e,
      selectedContent:temp,
      collectOneIsOpened: true
    })
    // console.log(this.state.collectOneSelected)
    // 删除一条收藏
    // this.setState({
    //   collectList: this.state.collectList.filter((_, i) => i !== e)
    // })
  }
  closeCollectOneEdit(){
    this.setState({
      collectOneIsOpened: false
    })
  }
  deleteCollectOneEdit = e =>{
    let arr = wx.getStorageSync("geci") || [];
    console.log(arr)
    let tempcontent = this.state.collectList_content.filter((_, i) => i !== this.state.collectOneSelected);
    let temptitle  = this.state.collectList_title.filter((_, i) => i !== this.state.collectOneSelected);
    // arr = arr.filter((_, i) => i !== this.state.collectOneSelected);
    wx.setStorageSync("geci", arr)
    this.setState({
      // collectList: this.state.collectList.filter((_, i) => i !== this.state.collectOneSelected),
      // collectList: arr,
      collectList_content:tempcontent,
      collectList_title:temptitle,
      collectOneIsOpened: false
    })
  }
  startSearchNext () {
    // console.log(this.collectOneIsOpened)
    let thisId = this.state.pageNum + 1
    this.setState({
      clearSearch:false,
      pageNum: thisId
    },this.startSearch)
  }
  startSearch0 (){
    this.setState({
      clearSearch:true,
      pageNum: 1,
      contentid:1
    },this.startSearch)
  }
  startSearch () { 
    if(this.state.search == '' || this.state.search == null){
      wx.showToast({
        title: '请输入词语...',
        icon: 'none',
        duration: 2000
      })
      return
    }
    
    wx.showLoading({
      title: '搜索中...',mask: true
    })
    let settime = setTimeout(function(){
      wx.hideLoading()
    },20000)
     
    var self = this
    Taro.request({
      url: 'https://www.btsousou.cn/td/'+self.state.search+'/'+self.state.pageNum+'/'+self.state.contentid, 
      data: {},
      header: {
        'content-type': 'application/json'
      },
      // success: function (res) {
      //   wx.hideLoading()
      //   let all = []
      //   for (let id in res.data.result){
      //     all.push(res.data.result[id].content)
      //   }
      //   self.setState({clist:all})
      // },
      
    }).then(res => {
          // console.log(res.data)
          clearTimeout(settime);
          wx.hideLoading()
          // 是否清空已经搜索的数据 重新搜索
          let all = []
          let all_content = []
          let all_title = []
          if(this.state.clearSearch == false){
            all = this.state.clist
            all_content = this.state.clist_content
            all_title = this.state.clist_title
          }
          
          for (let id in res.data.result){
            // let temp = []
            // temp.push(res.data.result[id].title)
            // temp.push(res.data.result[id].content)
            // all.push(temp)
            all_content.push(res.data.result[id].content)
            all_title.push(res.data.result[id].title)
          }
          // console.log(this.state.clist[0])
          // self.setState({clist:all})
          self.setState({clist_content:all_content,clist_title:all_title , contentid:res.data.page})

    }).catch(function(reason){
          // console.log(reason) 
          clearTimeout(settime);
          wx.hideLoading()
          wx.showToast({
            title: '搜索失败...',
            icon: 'none',
            duration: 2000
          })
    })
  }


  render () {
    let self = this;
    const oneline = [...this.state.clist.keys()] // 展开数组
    const collectOneLine = [...this.state.collectList.keys()] // 展开数组
    const listItems = oneline.map((oneline) => {   
      return <MYAtListItem class='oneline' key={String(oneline)} onClick={this.addOneCollect.bind(this,oneline)} title={String(this.state.clist[oneline][1])} note={'<<'+String(this.state.clist[oneline][0])+'>>'} />

    })
    const CollectLists = collectOneLine.map((collectOneLine) => {
      return <MYAtListItem key={String(collectOneLine)} title={String(this.state.collectList[collectOneLine][1])} note={'<<'+String(this.state.collectList[collectOneLine][0])+'>>'} onClick={this.showOneSelected.bind(this,collectOneLine)} />
    })
    return ( 
      
      <View style="background-color:#F2F2F2">
        <Image class='img' src={banner} mode="widthFix"/>
        <view  className='index'>
          <view style='width:100%;text-align:center;height:30px;'><text style="font-size:36px;text-align:center;font-weight:bold;line-height:36px;">押韵歌词</text></view>
          <view style='width:100%;text-align:center;margin-top:5px;'><text style="font-size:14px;text-align:center;">双押 | 三押 | 多押</text></view>
          <view style='width:100%;text-align:center;margin-top:5px;'><text style="font-size:14px;text-align:center;">版本：3.0.0，更新时间：2019.8.8</text></view>
          {/* <view style='text-align:center;margin-left:10px; margin-right:10px;padding:5px;background-color:#FFFFFF'><text style="font-size:14px;text-align:center;">更新：查询功能更加稳定</text></view> */}
          {/* <view style='width:90%;text-align:center;margin:5px auto;'><text style="font-size:14px;text-align:center;">自建的服务器，有时候会掉线，搜索不了可以联系底部联系方式。</text></view> */}
          <view class="section">
            <Input type='text' class="searchInput" auto-foucs placeholder='填入搜索的词语(中文不要有其他符号)' value={this.state.search} onInput={this.handelChange}/>
          </view>
          <view style="display:flex;margin-top:30px;">
            <Button type="primary" onClick={this.startSearch0} style="width:200px;margin-top:20px;margin-right:0;">
              搜索
            </Button>
            <Button type="default" onClick={this.collectClick} style="width:100px;margin-top:20px;margin-left:5px;">
              我的收藏
            </Button>
          </view>
          <Lyclistitem datatitle={this.state.clist_title} datacontent={this.state.clist_content} onAddone={this.onAddone.bind(this)}></Lyclistitem>
          <view class='card'>
            <view>
              {/* <MYAtList>
                {listItems}
              </MYAtList> */}
              {/* <view class="cardoneline_last">
                <Button type="default" onClick={this.startSearchNext} style="margin-left:20px;margin-right:20px;margin-top:30px;">
                  下一页
                </Button>
              </view> */}
              <ad unit-id="adunit-e200e9e5fe3165dc"></ad>
              <view style="display:flex;margin-top:30px;">
                <Button type="default" onClick={this.startSearchNext} style="width:200px;margin-top:20px;margin-right:0;">
                  下一页
                </Button>
                <Button type="default" onClick={this.collectClick} style="width:100px;height:100%;margin-top:20px;margin-left:5px;">
                  收藏
                </Button>
                <Button type="default" onClick={this.goTop} style="width:100px;height:100%;margin-top:20px;margin-left:5px;">
                  顶部
                </Button>
              </view>
              <view style='width:90%;text-align:center;margin:5px auto;'><text style="font-size:14px;text-align:center;">自建的服务器，有时候会掉线，搜索不了可以联系我QQ:719082908,或者微信：meishijie</text></view>
            </view>
          </view>
        </view>
        
        <AtFloatLayout
          isOpened={isOpened}
          title='我的收藏'
          onClose={ this.handleClose } >
          <LycCollectlistitem  datatitle={this.state.collectList_title} datacontent={this.state.collectList_content} onDeleteone={this.showOneSelected.bind(this)}></LycCollectlistitem>
          {/* {CollectLists} */}
          {/* <AtList>
            <AtListItem title='标题文字' onClick={this.closeModal} />
          </AtList> */}
        </AtFloatLayout>
         {/* 单个按钮  */}
         <AtModal isOpened={collectOneIsOpened}>
          <AtModalHeader>《{selectedContent[1]}》</AtModalHeader>
          <AtModalContent>
            <View className='modal-content'>
              {/* 编辑的词条内容 */}
              {/* {selectedContent[0]} */}
              {selectedContent[0]}
            </View>
          </AtModalContent>
          <AtModalAction>
            <Button onClick={this.closeCollectOneEdit.bind(this)}>
              返回
            </Button>
            <Button onClick={this.deleteCollectOneEdit.bind(this)}>
              删除
            </Button>
          </AtModalAction>
        </AtModal>
           

      </View>
    )
  }
}

